import proxyquire from 'proxyquire'
import * as chai from 'chai'
import * as sinon from 'sinon'

const expect = chai.expect

describe('installKubectl', function() {
    let stepToolkitStub: any
    let fsStub: any
    let installKubectlProxy: any

    beforeEach(function() {
        stepToolkitStub = {
            info: sinon.stub(),
            tool: {
                install: sinon.stub()
            },
            addPath: sinon.stub()
        }

        fsStub = {
            chmodSync: sinon.stub()
        }

        installKubectlProxy = proxyquire('../src/install', {
            '@flow-step/step-toolkit': stepToolkitStub,
            fs: fsStub
        }).installKubectl
    })

    afterEach(function() {
        sinon.restore()
    })

    it('should install kubectl with the correct version', async function() {
        const version = 'v1.20.0'
        const installPath = '/some/install/path'
        stepToolkitStub.tool.install.resolves(installPath)

        const result = await installKubectlProxy(version)

        expect(stepToolkitStub.info.calledWith(`Try to install the kubectl with version ${version}`)).to.be.true
        expect(stepToolkitStub.tool.install.calledWith('kubectl', version)).to.be.true
        expect(fsStub.chmodSync.calledWith(`${installPath}/kubectl-${version}`, 0o755)).to.be.true
        expect(stepToolkitStub.addPath.calledWith(installPath)).to.be.true
        expect(result).to.equal(`${installPath}/kubectl-${version}`)
    })

    it('should throw an error if installation fails', async function() {
        const version = 'v1.20.0'
        const error = new Error('Installation failed')
        stepToolkitStub.tool.install.rejects(error)

        try {
            await installKubectlProxy(version)
            expect.fail('Expected an error to be thrown')
        } catch (err) {
            // @ts-ignore
            expect(err.message).to.equal(`failed to install kubectl but err: ${error}`)
        }
    })
})
